package com.baseframe.sys.controller;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baseframe.common.annotation.SysLog;
import com.baseframe.common.annotation.VisitLog;
import com.baseframe.common.exception.RRException;
import com.baseframe.common.utils.R;
import com.baseframe.sys.entity.FrameAttachinfo;
import com.baseframe.sys.entity.FrameAttachstorage;
import com.baseframe.sys.entity.FrameUser;
import com.baseframe.sys.service.IFrameAttachinfoService;
import com.baseframe.sys.service.IFrameAttachstorageService;

/**
 * 
 *
 * @author xuxf
 */
@RestController
@RequestMapping("/frame/attachinfo")
public class FrameAttachinfoController extends AbstractController {

	@Autowired
	private IFrameAttachinfoService frameAttachinfoService;

	@Autowired
	private IFrameAttachstorageService frameAttachstorageService;

	/**
	 * 上传文件
	 */
	@SysLog(value="上传文件", type="新增")
	@RequestMapping("/upload")
	public R upload(@RequestParam("file") MultipartFile file,
			@RequestParam("id") String id) throws Exception {
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		String url = "";
		// 上传文件
		String suffix = file.getOriginalFilename().substring(
				file.getOriginalFilename().lastIndexOf("."));
		System.out.println("suffix=" + suffix);
		// String url = OSSFactory.build().uploadSuffix(file.getBytes(),
		// suffix);
		// System.out.println("url="+url);
		FrameUser user = getUser();

		FrameAttachinfo frameAttachinfo = new FrameAttachinfo();
		frameAttachinfo.setAttachguid(UUID.randomUUID().toString()
				.replace("-", ""));
		frameAttachinfo.setAttachfilename(file.getOriginalFilename());
		frameAttachinfo.setContenttype(suffix);
		frameAttachinfo.setAttachlength((int) file.getSize());
		frameAttachinfo.setClientguid(id);
		frameAttachinfo.setUploadtime(new Date());
		frameAttachinfo.setUploaduserguid(user.getUserguid());
		frameAttachinfo.setUploadusername(user.getLoginname());
		String attachstorageguid = UUID.randomUUID().toString()
				.replace("-", "");
		frameAttachinfo.setAttachstorageguid(attachstorageguid);

		FrameAttachstorage storage = new FrameAttachstorage();
		storage.setAttachguid(attachstorageguid);
		storage.setAttachfilename(file.getOriginalFilename());
		storage.setContenttype(suffix);
		storage.setContent(file.getBytes());
		storage.setClientguid(id);
		frameAttachinfoService.save(frameAttachinfo);
		frameAttachstorageService.save(storage);

		return R.ok().put("name", file.getOriginalFilename());
	}

	/**
	 *
	 */
	@RequestMapping("/getattachname/{clientguid}")
	public R getattachname(@PathVariable("clientguid") String clientguid) {
		FrameAttachinfo info = new FrameAttachinfo();
		List<FrameAttachinfo> list = frameAttachinfoService
				.findByClientguid(clientguid);
		if (list.size() > 0) {
			info = list.get(0);
		}

		return R.ok().put("info", info);
	}
	
	
	/**
	 *获取所有附件
	 */
	@RequestMapping("/getattachs/{clientguid}")
	public R getattachs(@PathVariable("clientguid") String clientguid) {
		List<FrameAttachinfo> list = frameAttachinfoService
				.findByClientguid(clientguid);

		return R.ok().put("info", list);
	}
	
	
	/**
	 *获取所有附件attachstorage
	 */
	@RequestMapping("/getattachstorages/{clientguid}")
	public R getattachstorages(@PathVariable("clientguid") String clientguid) {
		List<FrameAttachstorage> list = frameAttachstorageService
				.findByClientguid(clientguid);

		return R.ok().put("info", list);
	}
	
	

	/**
	 *
	 */
	@RequestMapping("/getattachstorage/{clientguid}")
	public R getattachstorage(@PathVariable("clientguid") String clientguid) {
		FrameAttachinfo info = new FrameAttachinfo();
		List<FrameAttachinfo> list = frameAttachinfoService
				.findByClientguid(clientguid);
		if (list.size() > 0) {
			info = list.get(0);
		}
		
		FrameAttachstorage storage = frameAttachstorageService.selectById(info
				.getAttachstorageguid());

		return R.ok().put("storage", storage);
	}

	/**
	 * 获取附件内容
	 */
	@RequestMapping("/getPicInfo/{attachguid}")
	public R getPicInfo(@PathVariable("attachguid") String attachguid,
			HttpServletResponse response) {
		FrameAttachinfo info = new FrameAttachinfo();
		info = frameAttachinfoService.selectById(attachguid);

		FrameAttachstorage storage = frameAttachstorageService.selectById(info
				.getAttachstorageguid());
		
		return R.ok().put("storage", storage);

	}
	
	/**
	 * 根据attachguid删除
	 */
	@SysLog(value="删除附件", type="删除")
	@RequestMapping("/del/{attachguid}")
	public R del(@PathVariable("attachguid") String attachguid) {
		FrameAttachinfo info = new FrameAttachinfo();
		info = frameAttachinfoService.selectById(attachguid);

//		FrameAttachstorage storage = frameAttachstorageService.selectById(info
//				.getAttachstorageguid());
		int ret  = frameAttachinfoService.deleteAttach(info);
		
		 return ret == 0 ? R.ok() : R.error("操作失败，请联系管理员");

	}
	
	
	
	/**
	 * 根据clientguid删除附件
	 */
	@SysLog(value="删除附件", type="删除")
	@RequestMapping("/deleteAttachByClientGuid/{clientguid}")
	public R deleteAttachByClientGuid(@PathVariable("clientguid") String clientguid) {

		int ret  = frameAttachinfoService.deleteByClientguid(clientguid);
		
		 return ret == 0 ? R.ok() : R.error("操作失败，请联系管理员");

	}
	
	
	@VisitLog("下载附件")
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	  public void download(HttpServletResponse res,String attachguid) {
		
		System.out.println("clientguid"+attachguid);
		FrameAttachstorage storage = frameAttachstorageService.selectById(attachguid);
		
	    String fileName = storage.getAttachfilename();
	    res.setHeader("content-type", "application/octet-stream");
	    res.setContentType("application/octet-stream");
	    res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
	    byte[] buff = storage.getContent();
	    BufferedInputStream bis = null;
	    OutputStream os = null;
	    try {
	      os = res.getOutputStream();
//	      bis = new BufferedInputStream(new FileInputStream(new File("d://"
//	          + fileName)));
//	      int i = bis.read(buff);
//	      while (i != -1) {
	        os.write(buff, 0, buff.length);
	        os.flush();
//	        int i = bis.read(buff);
//	      }
	    } catch (IOException e) {
	      e.printStackTrace();
	    } finally {
	      if (bis != null) {
	        try {
	          bis.close();
	        } catch (IOException e) {
	          e.printStackTrace();
	        }
	      }
	    }
	    System.out.println("success");
	  }
	
	
	
	
	
	
	

}
